Popular Searches
Popular Course Categories
Popular Courses

Implementing JSP Error Pages and Exception Handling

Implementing JSP Error Pages and Exception Handling

JavaServer Pages (JSP) Development

Implementing JSP Error Pages and Exception Handling

Course: Advanced Java Training

Topic: Implementing JSP Error Pages and Exception Handling

Course Link: Advanced Java Training Course

Demo Link: Register for a Course Demo

JustAcademy Homepage: Visit JustAcademy


1. Introduction to JSP Error Handling

JavaServer Pages (JSP) is a server-side technology used to create dynamic web pages. During request processing, a JSP page may encounter exceptions caused by invalid input, missing resources, database failures, incorrect type conversions, or programming errors.

JSP error handling is the process of detecting and managing these failures so that an application can respond appropriately instead of displaying confusing technical messages or abruptly terminating a request.

JSP supports error handling through page directives, Java exception-handling mechanisms, configured error pages, and integration with the Servlet API. A well-designed application displays a helpful message to the user while recording technical details securely for developers.

Why Is Error Handling Important?

  • Improves the user experience when an unexpected problem occurs.
  • Prevents internal implementation details from being exposed.
  • Helps developers diagnose and resolve application defects.
  • Supports consistent handling of HTTP error responses.
  • Reduces the risk of displaying stack traces or sensitive information.
  • Makes applications easier to maintain and troubleshoot.

2. Learning Objectives

  • Understand exceptions and errors in JSP applications.
  • Learn the purpose of the errorPage and isErrorPage attributes.
  • Implement custom JSP error pages.
  • Use Java's try-catch-finally structure appropriately.
  • Understand how servlet-level error handling complements JSP error pages.
  • Distinguish client errors, server errors, and application exceptions.
  • Apply secure logging and user-friendly error-message practices.
  • Build a practical example with a JSP page and a custom error page.

3. Understanding Exceptions in JSP

An exception is an event that interrupts the normal flow of program execution. In a JSP application, exceptions may occur inside Java code embedded in a JSP, in a Java class called by the JSP, or in other application components.

Common Causes of JSP Exceptions

Cause Example Possible Solution
Arithmetic error Dividing an integer by zero. Validate the divisor before performing the calculation.
Null reference Calling a method on a null object. Check whether the object exists before using it.
Invalid input Converting non-numeric text to an integer. Validate input and handle conversion failures.
Database failure Connection timeout or SQL execution failure. Handle database exceptions and log useful diagnostics.
Missing resource Attempting to access a file that does not exist. Verify the resource path and handle missing-resource cases.
JSP compilation error Invalid JSP syntax or missing dependencies. Correct the syntax or dependency configuration.
Authorization failure A user attempts to access a restricted resource. Apply authorization checks and return an appropriate status.

4. Exception Handling Using try-catch

Java provides try and catch blocks to handle exceptions that a program can reasonably recover from. A JSP scriptlet can use these blocks, although modern applications should generally perform business logic and exception handling in Java classes or servlets rather than directly in the JSP view.

Basic Syntax

<%
try {
    // Code that may throw an exception
} catch (Exception e) {
    // Handle the exception appropriately
}
%>

Example: Handling ArithmeticException

<%
int numerator = 100;
int denominator = 0;
String message;

try {
    int result = numerator / denominator;
    message = "Result: " + result;
} catch (ArithmeticException e) {
    message = "The calculation could not be completed.";
}
%>
<p><%= message %></p>

Explanation:

  • The try block contains the calculation.
  • Dividing an integer by zero causes an ArithmeticException.
  • The catch block handles the expected failure.
  • The page displays a simple message rather than an exception stack trace.

For production code, prefer catching specific exceptions where possible instead of catching every exception indiscriminately.

5. Understanding the finally Block

The finally block is used for cleanup operations that should normally run whether an exception occurs or not. Examples include releasing resources and restoring temporary state.

<%
java.io.BufferedReader reader = null;

try {
    // Perform an operation that may fail
    reader = new java.io.BufferedReader(
        new java.io.StringReader("JSP error handling")
    );
    String line = reader.readLine();
} catch (java.io.IOException e) {
    // Record or handle the expected I/O failure
} finally {
    if (reader != null) {
        try {
            reader.close();
        } catch (java.io.IOException e) {
            // Record cleanup failure if necessary
        }
    }
}
%>

In modern Java, try-with-resources is usually preferred for closing resources that implement AutoCloseable. Resource handling and business logic should normally be placed in Java classes rather than JSP pages.

6. What Is a JSP Error Page?

A JSP error page is a page configured to handle eligible unhandled exceptions from another JSP page. It allows an application to display a consistent message when request processing fails.

JSP provides two important page directive attributes for this purpose:

  • errorPage: identifies the resource to which an eligible unhandled exception should be forwarded.
  • isErrorPage: marks a JSP as an error-handling page and makes the implicit exception object available.

These settings are part of JSP's page directive configuration. Read the Jakarta Server Pages specification for the formal rules governing JSP error handling.

7. Using the errorPage Attribute

The errorPage attribute specifies the destination for handling eligible uncaught exceptions from the JSP page.

Syntax

<%@ page errorPage="error.jsp" %>

Example: main.jsp

<%@ page contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"
    errorPage="error.jsp" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JSP Exception Demo</title>
</head>
<body>
    <h1>JSP Exception Demonstration</h1>
    <%
        int number = 10 / 0;
    %>
    <p>Result: <%= number %></p>
</body>
</html>

When the integer division throws an uncaught ArithmeticException, the JSP container attempts to forward the request to the configured error page. The code after the failing statement is not executed normally.

Important: Error-page forwarding can fail or behave differently if the response has already been committed. Avoid flushing or writing large amounts of output before an operation that may fail.

8. Using the isErrorPage Attribute

The isErrorPage attribute indicates whether a JSP page is intended to handle errors.

Syntax

<%@ page isErrorPage="true" %>

When this attribute is set to true, the JSP page can access the implicit exception object containing the relevant throwable, when supplied by the container.

Example: error.jsp

<%@ page contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"
    isErrorPage="true" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Application Error</title>
</head>
<body>
    <h1>Something went wrong</h1>
    <p>We could not complete your request. Please try again later.</p>
</body>
</html>

This page displays a general message and does not reveal the technical exception details. The container also makes error information available through request attributes as defined by the applicable servlet specification.

9. Difference Between errorPage and isErrorPage

Feature errorPage isErrorPage
Purpose Specifies the error-handling destination. Marks the current JSP as an error page.
Typical value "error.jsp" "true"
Where it is configured On a JSP page that may throw an unhandled exception. On the JSP that handles the error.
Exception object Does not itself expose the implicit exception object on the source page. Makes the implicit exception object available.
Example <%@ page errorPage="error.jsp" %> <%@ page isErrorPage="true" %>

10. Accessing Exception Details Safely

The exception object can provide diagnostic details to server-side error-handling code. However, displaying its message or stack trace directly to visitors may expose sensitive implementation information.

A safer error page displays a generic message:

<%@ page isErrorPage="true"
    contentType="text/html; charset=UTF-8" %>
<h1>Unable to process your request</h1>
<p>Please try again later or contact support if the issue continues.</p>

If technical details are needed for troubleshooting, log them on the server using an application logging framework. Do not assume that the error page is a secure place to expose exception messages, SQL queries, file paths, credentials, or stack traces.

11. Handling Different Types of Exceptions

Different failures require different responses. Catch exceptions when the application can take a useful action; allow unexpected failures to reach centralized error handling after they have been logged appropriately.

Exception Type Typical Situation Handling Strategy
ArithmeticException Integer division by zero. Validate the calculation and show a clear message.
NumberFormatException Invalid numeric input. Validate input and ask the user to correct it.
NullPointerException Unexpected null reference. Investigate the cause, fix the defect, and handle valid missing-data cases explicitly.
IOException File or stream operation fails. Handle the I/O failure and release resources safely.
SQLException Database access fails. Handle it in the data-access layer and log appropriate diagnostics.
ServletException Servlet processing fails. Use controller-level or container-level error handling.

Do not use exception handling as a replacement for normal input validation. For example, check whether a required form field is empty before attempting to convert it into a number.

12. JSP Error Pages vs. Servlet Error Pages

JSP page directives are useful for exceptions that originate during JSP processing. Web applications can also configure centralized error handling for HTTP status codes and uncaught exceptions through deployment configuration or servlet-based mechanisms.

Approach Purpose Typical Use
JSP errorPage Handles eligible uncaught exceptions from a JSP page. Page-specific exception handling.
Servlet web.xml error-page configuration Maps exception types or HTTP status codes to error resources. Application-wide error handling.
Servlet or controller exception handling Handles errors at the request-processing layer. Business operations, validation, and application workflows.
Logging framework Records technical details for investigation. Diagnostics, monitoring, and incident analysis.

13. Configuring Error Pages in web.xml

The deployment descriptor, WEB-INF/web.xml, can map exceptions and HTTP status codes to error resources. This provides centralized configuration for failures that are not handled by a page-specific error directive.

Example: Mapping an HTTP Status Code

<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
         version="6.0">
    <error-page>
        <error-code>404</error-code>
        <location>/errors/404.jsp</location>
    </error-page>
    <error-page>
        <error-code>500</error-code>
        <location>/errors/500.jsp</location>
    </error-page>
</web-app>

This example maps HTTP 404 responses to a not-found page and HTTP 500 responses to a server-error page. The descriptor version must be compatible with the servlet container and the rest of the deployment configuration.

Example: Mapping an Exception Type

<error-page>
    <exception-type>java.lang.Exception</exception-type>
    <location>/errors/general-error.jsp</location>
</error-page>

Exception mappings should be chosen carefully. A broad mapping may handle many failures, but more specific mappings can be useful when the application has a meaningful recovery path. Ensure that error pages themselves do not cause further errors.

14. Understanding HTTP Error Status Codes

HTTP status codes communicate the result of a request to the client. Error pages should be paired with appropriate status codes instead of returning a successful status for every failure.

Status Code Meaning Example
400 Bad Request The request contains invalid data.
401 Unauthorized Authentication is required or has failed.
403 Forbidden The user is not permitted to access a resource.
404 Not Found The requested page or resource does not exist.
405 Method Not Allowed The endpoint does not support the requested HTTP method.
500 Internal Server Error An unexpected server-side failure occurred.
503 Service Unavailable The service is temporarily unable to handle requests.

Use the status code that accurately represents the failure. For example, a missing resource normally calls for a 404 response, while an unexpected server-side exception generally results in a 500 response.

15. Logging Exceptions in Java Applications

Logging allows developers and support teams to investigate failures without exposing sensitive technical details to end users. A logging framework such as SLF4J with a compatible implementation can record the exception and its stack trace.

Example: Logging an Exception in a Java Service

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CourseService {
    private static final Logger logger =
        LoggerFactory.getLogger(CourseService.class);

    public void processCourse() {
        try {
            // Perform the required operation
        } catch (RuntimeException e) {
            logger.error("Unable to process course request", e);
            throw e;
        }
    }
}

This example logs the exception and rethrows it so that an appropriate higher-level component can handle it. The exact exception type and recovery behavior should match the operation being performed.

Logging Best Practices

  • Record enough context to diagnose the failure without storing unnecessary personal data.
  • Use appropriate log levels such as INFO, WARN, and ERROR.
  • Avoid logging passwords, session tokens, authentication secrets, and sensitive form data.
  • Do not silently swallow exceptions.
  • Avoid logging the same exception repeatedly at every layer unless each log adds useful context.
  • Restrict access to logs and follow the organization's retention requirements.

16. A Complete JSP Error-Handling Example

This example demonstrates page-specific error handling. It uses a main JSP page, an error JSP, and a simple form for testing. It is intended for learning; in production, move calculations and other business logic to a servlet or service class.

Step 1: Create index.jsp

<%@ page contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JSP Error Handling Demo</title>
</head>
<body>
    <h1>Division Calculator</h1>
    <form action="calculate.jsp" method="get">
        <label for="a">Numerator:</label>
        <input type="number" id="a" name="a" required>
        <label for="b">Denominator:</label>
        <input type="number" id="b" name="b" required>
        <button type="submit">Calculate</button>
    </form>
</body>
</html>

Step 2: Create calculate.jsp

<%@ page contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"
    errorPage="error.jsp" %>
<%
    String aValue = request.getParameter("a");
    String bValue = request.getParameter("b");

    if (aValue == null || bValue == null
            || aValue.trim().isEmpty()
            || bValue.trim().isEmpty()) {
        throw new IllegalArgumentException("Required input is missing");
    }

    int a = Integer.parseInt(aValue);
    int b = Integer.parseInt(bValue);

    if (b == 0) {
        throw new ArithmeticException("Division by zero");
    }

    int result = a / b;
%>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Calculation Result</title>
</head>
<body>
    <h1>Calculation Result</h1>
    <p>Result: <%= result %></p>
    <a href="index.jsp">Try another calculation</a>
</body>
</html>

In this example, invalid numeric input or a zero denominator may produce an exception that is routed to the configured error page. A production implementation should validate input in a controller and return a suitable response for expected user errors instead of treating all validation failures as server errors.

Step 3: Create error.jsp

<%@ page contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"
    isErrorPage="true" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Request Error</title>
</head>
<body>
    <h1>Unable to complete the calculation</h1>
    <p>Check your input and try again. If the problem continues, contact support.</p>
    <a href="index.jsp">Return to calculator</a>
</body>
</html>

The error page intentionally avoids displaying the exception's message or stack trace. For a production application, log diagnostic details securely and distinguish invalid user input from unexpected application failures.

17. Exception Handling in Servlets

Although JSP page directives can handle exceptions arising from JSP processing, servlets are generally a better place for request validation, service invocation, and control flow.

Example: Handling an Invalid Number

import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@WebServlet("/calculate")
public class CalculateServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response)
            throws ServletException, IOException {
        String value = request.getParameter("number");

        try {
            int number = Integer.parseInt(value);
            request.setAttribute("result", number * 2);
            request.getRequestDispatcher("/result.jsp")
                   .forward(request, response);
        } catch (NumberFormatException e) {
            response.sendError(
                HttpServletResponse.SC_BAD_REQUEST,
                "Invalid number"
            );
        }
    }
}

This servlet validates the request parameter, prepares a result for the view, and forwards valid requests to a JSP. Invalid input produces a 400 Bad Request response. The JSP then focuses on displaying the result rather than handling request-processing logic.

18. Common JSP Error-Handling Mistakes

Mistake Why It Is a Problem Recommended Practice
Displaying stack traces to users May expose application internals and sensitive details. Display a generic message and log technical details securely.
Using only a catch-all exception handler May hide the real cause of failures. Catch specific exceptions where recovery is possible.
Ignoring exceptions Failures can go undetected and make debugging difficult. Handle, log, or propagate the exception appropriately.
Writing output before redirecting The response may already be committed. Make routing decisions before generating the response body.
Putting database logic in JSP Makes the application harder to test and maintain. Use a data-access layer and service classes.
Returning status 200 for every error Clients and monitoring tools may interpret failures as success. Use the appropriate HTTP status code.
Failing to validate input Invalid values may trigger avoidable exceptions. Validate request data before processing.
Creating an error page that also fails The original failure may become harder to diagnose. Keep error pages simple and test them separately.

19. Best Practices for JSP Exception Handling

  • Use the errorPage directive when page-specific JSP exception handling is appropriate.
  • Set isErrorPage="true" on a JSP that is intended to receive the implicit exception object.
  • Use centralized error mappings for application-wide HTTP status codes and exception types where appropriate.
  • Validate request data before using it in calculations, queries, or business operations.
  • Use meaningful messages for users without exposing internal implementation details.
  • Log unexpected failures through a logging framework.
  • Preserve appropriate HTTP status codes.
  • Avoid committing the response before operations that may require forwarding to an error page.
  • Keep error-handling pages simple and independent of complex application logic.
  • Use servlets, controllers, and service classes for request processing and business logic.
  • Test both successful requests and failure scenarios.

20. Practical Exercises

  1. Create a JSP page that performs division and handles division-by-zero errors.
  2. Configure a custom error page using the errorPage attribute.
  3. Use isErrorPage="true" and verify that the implicit exception object is available.
  4. Build a form that accepts a number and handles invalid numeric input.
  5. Configure a 404 error page in web.xml.
  6. Configure a 500 error page and test how unexpected server failures are displayed.
  7. Implement server-side logging for an exception in a Java service class.
  8. Refactor a JSP containing business logic into a servlet and a separate JSP view.

21. Mini Project: Student Registration Error Handling

Objective: Develop a student registration workflow with input validation, exception handling, and user-friendly error pages.

Project Requirements

  • Create a registration form for student name, email, and course.
  • Validate required fields on the server.
  • Display useful validation messages for incorrect input.
  • Use a servlet to process the registration request.
  • Handle unexpected service or database failures.
  • Configure appropriate error pages for 404 and 500 responses.
  • Log technical exceptions without exposing them to users.
  • Use JSP for the form, result page, and error-page presentation.

Expected Outcome

The project should demonstrate request validation, exception propagation, JSP error directives, centralized error handling, appropriate HTTP status codes, and separation of presentation from business logic.

22. Interview Questions and Answers

Q1. What is JSP error handling?

It is the process of managing exceptions that occur during JSP processing and displaying an appropriate response or forwarding the request to an error resource.

Q2. What is the purpose of the errorPage attribute?

It identifies a resource to which eligible uncaught exceptions from the JSP page can be forwarded for error processing.

Q3. What does isErrorPage="true" do?

It marks the JSP as an error page and makes the implicit exception object available.

Q4. Can an error page access the original exception?

Yes. A properly configured JSP error page can access the throwable through the implicit exception object. Error information is also made available through servlet request attributes according to the applicable specification.

Q5. What is the difference between try-catch and a JSP error page?

try-catch handles exceptions locally in Java code. A JSP error page handles eligible exceptions that remain uncaught during JSP processing.

Q6. Why should stack traces not be shown to users?

They may reveal internal paths, implementation details, query information, or other data that could help an attacker. Technical details should be logged securely.

Q7. What is the role of web.xml in error handling?

It can map HTTP status codes or exception types to error resources, enabling centralized error handling across an application.

Q8. What is the difference between HTTP 404 and HTTP 500?

HTTP 404 indicates that the requested resource was not found. HTTP 500 indicates an unexpected server-side failure.

Q9. Why is logging important in exception handling?

Logging records diagnostic information needed to investigate and resolve failures without exposing technical details to end users.

Q10. Should business logic be placed in JSP pages?

Generally, no. Business logic should be placed in servlets, controllers, and service classes, while JSP should focus on rendering the view.

23. Quick Revision Checklist

  • Understand exceptions that can occur during JSP processing.
  • Know the purpose of try, catch, and finally.
  • Understand the errorPage and isErrorPage directives.
  • Know how the implicit exception object is used on an error page.
  • Understand centralized error mappings in web.xml.
  • Use appropriate HTTP error status codes.
  • Log unexpected exceptions securely.
  • Do not expose stack traces or sensitive information to users.
  • Validate input before processing it.
  • Separate JSP presentation from application business logic.

Conclusion

Implementing JSP error pages and exception handling is an important part of developing reliable Advanced Java web applications. The errorPage and isErrorPage directives support page-level exception handling, while servlet-based mechanisms and web.xml mappings can provide broader application-level coverage. By validating input, logging failures securely, returning appropriate HTTP status codes, and displaying clear user-friendly messages, developers can build applications that are easier to troubleshoot, maintain, and secure.

Continue learning through the Advanced Java Training Course, register for a course demo, or visit the JustAcademy homepage.

Previous Next
whatsapp